﻿using System;
using System.Windows;
using System.Data;
using System.Xml;
using System.Configuration;

using Microsoft.VisualBasic.ApplicationServices;

// need those for query string parameters
using System.Web;
using System.Collections.Specialized;
using System.Deployment.Application;


namespace BadHabit.Factory {

    /// <summary>
    /// The entry point to make it a singleton.
    /// </summary>
    public class SingletonEntryPoint {

        [STAThread]
        public static void Main(string[] args) {
            string[] newArgs = new String[4];

                        
            NameValueCollection parameters = GetQueryStringParameters();


            // ServerUrl Parameter
            if (!String.IsNullOrEmpty(parameters["ServerUrl"]))
                newArgs[0] = parameters["ServerUrl"];
            else
                newArgs[0] = "DEFAULT";

            // ProjectNumber parameter            
            if(!String.IsNullOrEmpty(parameters["ProjectNumber"]))            
                newArgs[1] = parameters["ProjectNumber"];
            else
                newArgs[1] = "-1";

            
            if(!String.IsNullOrEmpty(parameters["TaskId"]))            
                newArgs[2] = parameters["TaskId"];
            else
                newArgs[2] = "-1";

            if (!String.IsNullOrEmpty(parameters["adminAccessKey"]))
                newArgs[3] = parameters["adminAccessKey"];
            else
                newArgs[3] = String.Empty;



            SingleInstanceManager manager = new SingleInstanceManager();        
            manager.Run(newArgs);
        }


        
        public static NameValueCollection GetQueryStringParameters() {
            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments == null)
                return new NameValueCollection();

            if(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData==null)
                return new NameValueCollection();

            string url = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];            
            if (url.IndexOf('?') >= 0) {                
                return HttpUtility.ParseQueryString(url.Substring(url.IndexOf('?')));
            }

            return new NameValueCollection();
        }

    }

    // Using VB bits to detect single instances and process accordingly:
    //  * OnStartup is fired when the first instance loads
    //  * OnStartupNextInstance is fired when the application is re-run again
    //    NOTE: it is redirected to this instance thanks to IsSingleInstance
    public class SingleInstanceManager : WindowsFormsApplicationBase {
        
        BadHabit.Factory.Client app;

    
        public SingleInstanceManager() {
            this.IsSingleInstance = true;
           
        }

        /// <summary>
        /// On startup create the Factory application and runs it.
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e) {
            // First time app is launched
            app = new BadHabit.Factory.Client();            
            try {
                app.Run();
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, "Unexpected Error");
            }

            return false;
        }

        /// <summary>
        /// On next instance, activate the old instance.
        /// </summary>
        /// <param name="eventArgs"></param>
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {            
            base.OnStartupNextInstance(e);
            CallActivate(e.CommandLine);            
        }

        private void CallActivate(System.Collections.ObjectModel.ReadOnlyCollection<string> args) {
                        
            // if parameter 1 was informed (ServerUrl)
            if (args.Count > 0) {
                if (!args[0].Equals("DEFAULT")) {
                    BadHabit.Factory.Properties.Settings.Default.ProjectWebServiceURL = args[0];
                    Client.SetUpService();
                }
            }
            
            // if parameter 2 was informed (ProjectNumber)
            if (args.Count > 1) {
                int projectNumber = -1;
                if (Int32.TryParse(args[1], out projectNumber)) {
                    if (projectNumber > 0) {
                        Client.ShowMainWindow(projectNumber);
                        return;
                    }                    
                }
            }

            if (args.Count > 2) {
                int taskId = -1;                
                if (Int32.TryParse(args[2], out taskId)) {                    
                    if (taskId > 0) {                        
                        Windows.TaskDetail w = new Windows.TaskDetail(taskId);
                        w.Show();
                        return;
                    }                    
                }
            }
         
            if (args.Count > 3) {
                if (!String.IsNullOrEmpty(args[3])) {
                    BadHabit.Factory.Properties.Settings.Default.UserMemberId = "FACTORY\\admin";
                    BadHabit.Factory.Properties.Settings.Default.UserAccessKey = args[3];
                    BadHabit.Factory.Properties.Settings.Default.UseWindowsAuthentication = false;                    
                }
            }

            
                
            Client.ShowMainWindow();
                
        }
    }

  
}